using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Xml.Xsl;
using Microsoft.SharePoint;
using System.Web;
using Microsoft.SharePoint.Utilities;

namespace IWCommunity.Blogs.WebControls
{
    public class PostList : BaseQueryControl
    {
        private Nullable<bool> _trimPostBody;

        public Nullable<bool> TrimPostBody
        {
            get { return (_trimPostBody == true); } //? BlogContext.Current.Settings.TrimPostBodyOnLists : _trimPostBody; }
            set { _trimPostBody = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

          //  SPList oPost = Web.Lists["Posts"];
           // SPField oField = oPost.Fields["Category"];

            ViewFieldsXML += "<FieldRef Name='Body'/><FieldRef Name='NumComments'/><FieldRef Name='PublishedDate'/><FieldRef Name='PostCategory'/><FieldRef Name='FileDirRef'/><FieldRef Name='BlogTitleForUrl'/><FieldRef Name='CategoriesAsText' Nullable='True' /><FieldRef Name='NumLinkbacks' Nullable='TRUE'/>";
            QueryXML = "<OrderBy><FieldRef Name='PublishedDate' Ascending='FALSE'/></OrderBy>";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["c"]))
                QueryXML = string.Format("<Where><Eq><FieldRef Name='PostCategory'/><Value Type='Text'>{0}</Value></Eq></Where>", HttpContext.Current.Request["c"]) + QueryXML;
            else if (!string.IsNullOrEmpty(HttpContext.Current.Request["m"]))
            {
                DateTime dtMonthStart = new DateTime(int.Parse(Page.Request["y"]), int.Parse(Page.Request["m"]), 1, 0, 0, 0);
                string sStart = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtMonthStart.AddMinutes(-1));
                string sEnd = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtMonthStart.AddMonths(1).AddMinutes(1)); 
                
                QueryXML = string.Format("<Where><And><Lt><FieldRef Name='PublishedDate'/><Value Type='DateTime'>{0}</Value></Lt><Gt><FieldRef Name='PublishedDate'/><Value Type='DateTime'>{1}</Value></Gt></And></Where>", sEnd, sStart) + QueryXML;
            }

            SPList oList = SPContext.Current.Web.Lists["Posts"];
            ListsXML = string.Format("<Lists><List ID='{0}'/></Lists>", oList.ID.ToString());

            Transform.XslArguments.AddParam("TrimPosts", "", TrimPostBody);
        }

    }
}
